package com.acme.bankapp.domain.accounting;



/**
 * Account with overdraft
 *
 */
public class CheckingAccount extends AbstractAccount{
	
	public static final double DEFAULT_INITIAL_MIN_OVERDRAFT = -100;

	private double overdraft = 0;
	private double minOverdraft = 0;

	public CheckingAccount(double balance, double minOverdraft) {
		super(balance);
		if(minOverdraft > 0) throw new IllegalArgumentException("minOverdraft shouldn't be greater then 0");
		this.minOverdraft = minOverdraft;
	}
	
	public CheckingAccount(){
		this(DEFAULT_INITIAL_BALANCE, DEFAULT_INITIAL_MIN_OVERDRAFT);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void withdraw(double x) throws OverDraftLimitExceededException {
		if (balance > x) {
			balance -= x;
		} else if (overdraft - x + balance >= minOverdraft) {
			overdraft = overdraft - x + balance;
			balance = 0;
		} else {
			throw new OverDraftLimitExceededException(x,this.maximumAmountToWithdraw());
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void deposit(double x) {
		if(overdraft < 0){
			x += overdraft;
		}
		if(x > 0){
			overdraft = 0;
		}else{
			overdraft = x;
		}		
		super.deposit(x);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public double maximumAmountToWithdraw() {
		return balance + overdraft - minOverdraft;
	}

}
